<?php
class template {
    private $theme;
    private $vars = array();
    private $globals;

    function __construct($theme) {
        $this->globals = array();
        $this->theme = $theme;
    }

    public function set($name,$val){
        if(isset($this->vars[$name])) {
            throw new Exception('Unable to set var `' . $name . '`. Already set.');
        }
        $this->vars[$name] = $val;
        return TRUE;
    }

    public function setGlobal($name,$val){
        if(isset($this->globals[$name])) {
            throw new Exception('Unable to set var `' . $name . '`. Already set.');
        }
        $this->globals[$name] = $val;
        return TRUE;
    }

    public function del($name){
        unset($this->vars[$name]);
        return true;
    }

    public function add($name,$val){
        if(!isset($this->vars[$name])) {
            throw new Exception('Var `' . $name . '` Is not set yet.');
        }
        $this->vars[$name].=$val;
        return true;
    }

    public function g_add($name,$val){
        if(!isset($this->globals[$name])) {
            throw new Exception('Var `' . $name . '` Is not set yet.');
        }
        $this->globals[$name].=$val;
        return true;
    }

    public function apply($tpl){
        ob_start();
        $path = site_path . 'themes/'. $this->theme .'/'. $tpl . '.tpl.php';
	if (file_exists($path) == false) {
            trigger_error ('Template `' . $tpl . '` does not exist.', E_USER_NOTICE);
            return false;
	}

	// Load variables
	foreach ($this->vars as $key => $value) {
		$$key = $value;
                unset($this->vars[$key]);
	}

	include ($path);
        $p = ob_get_contents();
        ob_end_clean();
        return $p;

    }

    public function apply_sys($tpl){
        ob_start();
        $path = site_path . 'themes/sys_tpl/'. $tpl . '.tpl.php';
	if (file_exists($path) == false) {
            trigger_error ('Template `' . $tpl . '` does not exist.', E_USER_NOTICE);
            return false;
	}

	// Load variables
	foreach ($this->vars as $key => $value) {
		$$key = $value;
                unset($this->vars[$key]);
	}

	include ($path);
        $p = ob_get_contents();
        ob_end_clean();
        return $p;

    }


    public function drawPage(){
        // define path to stylesheets(?)
        $theme_url = site_url . 'themes/'. $this->theme .'/';

        $path = site_path . 'themes/'. $this->theme .'/page.tpl.php';
	if (file_exists($path) == false) {
            trigger_error ('Template `' . $tpl . '` does not exist.', E_USER_NOTICE);
            return false;
	}

	// Load variables
	foreach ($this->globals as $key => $value) {
		$$key = trim($value);
	}
	include ($path);
    }
}
?>
